import hljs from 'highlight.js';
import DOMPurify from 'dompurify';
import mk from 'markdown-it-katex';
import MarkdownIt from 'markdown-it';
import sanitizer from "markdown-it-sanitizer";
const markdown = new MarkdownIt({
	html: true, // 允许 HTML 标签
	emoji: true, // 允许 emoji
	tabels: true, // 允许表格
	linkify: false, // 自动转换链接
	typographer: true, // 优化排版
	highlight: (str, lang) => {
		// 代码高亮逻辑
		if (lang && hljs.getLanguage(lang)) {
			try {
				return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`;
			} catch (__) {}
		}
		// 未指定语言时，自动检测
		return `<pre class="hljs" style="background: #fafafa;"><code>${hljs.highlightAuto(str).value}</code></pre>`;
	}
});
// 启用 KaTeX 插件
markdown.use(mk, {
	macros: {
		// 物理符号
		"\\e": "\\mathrm{e}",
		"\\ii": "\\mathrm{i}",
		"\\dd": "\\mathop{}\\!\\mathrm{d}",
		"\\bra": ["\\left\\langle #1 \\right|", 1],
		"\\ket": ["\\left| #1 \\right\\rangle", 1],
		"\\vect": ["\\mathbf{#1}", 1],
		"\\tensor": ["\\underline{\\underline{#1}}", 1],
		"\\ev": ["\\left\\langle #1 \\right\\rangle", 1],

		// 数学符号
		"\\Z": "\\mathbb{Z}",
		"\\Q": "\\mathbb{Q}",
		"\\C": "\\mathbb{C}",
		"\\R": "\\mathbb{R}",
		"\\abs": ["\\left| #1 \\right|", 1],
		"\\pd": ["\\frac{\\partial #1}{\\partial #2}", 2],
		"\\matrix": "\\begin{pmatrix} #1 \\\\ #2 \\end{pmatrix}",
		"\\pmatrix": ["\\begin{pmatrix} #1 \\\\ #2 \\end{pmatrix}", 2],
		"\\eq": ["\\begin{equation} #1 \\end{equation}", 1],

		// 化学
		"\\xrightarrow": ["\\overset{#2}{\\longrightarrow}", 2],
		"\\chem": ["\\mathrm{#1}", 1],

		// 统计力学
		"\\kB": "k_{\\text{B}}",
		"\\mean": ["\\left\\langle #1 \\right\\rangle", 1],
		"\\var": ["\\operatorname{Var}(#1)", 1],
		"\\cov": ["\\operatorname{Cov}(#1, #2)", 2],
		"\\dB": ["\\, \\text{dB}", 0],

		// 动态宏
		"\\unit": (ctx) => {
			const args = ctx.consumeArgs(1);
			return `\\, \\text{${args[0]}}`;
		},
		"\\grad": (context) => {
			const args = context.consumeArgs(1); // 读取参数
			return `\\nabla ${args[0]}`;
		},
	},
	throwOnError: false,
	displayMode: true
});

// markdown.renderer.rules.html_bloc
console.log(markdown.renderer.rules);

// 自定义链接处理（设置 target="_blank"）
markdown.renderer.rules.link_open = (tokens, idx, options) => {
	let token = tokens[idx];
	let hrefIndex = token.attrIndex('href');
	if (hrefIndex >= 0) {
		token.attrPush(['target', '_blank']);
		token.attrPush(['rel', 'noopener noreferrer']);
	}
	return markdown.renderer.renderToken(tokens, idx, options);
}
export function parseMarkdown(content) {
	let rawHtml = markdown.render(content);
	return DOMPurify.sanitize(completeHtmlStructure(rawHtml));
}


/**
 * 补全不完整的HTML字符串结构
 * @param {string} html 不完整的HTML字符串
 * @returns {string} 补全后的完整HTML字符串
 */
export function completeHtmlStructure(html) {
	// 处理空字符串情况
	if (!html || typeof html !== 'string') return '';
	// 使用DOMParser解析HTML（浏览器会自动修复部分结构）
	const parser = new DOMParser();
	const regex = /<([a-zA-Z0-9_-]+)>\s*<\/\1>/g;
	const doc = parser.parseFromString(html, 'text/html');
	let htmlString = doc.body.innerHTML;
	while (regex.test(htmlString)) {
		htmlString = htmlString.replace(regex, '');
	}
	return htmlString;
}